package com.example.as_sum.glide;

import android.app.ActivityManager;
import android.content.Context;
import android.os.Build;

import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.bitmap_recycle.LruBitmapPool;
import com.bumptech.glide.load.engine.cache.DiskLruCacheFactory;
import com.bumptech.glide.load.engine.cache.ExternalCacheDiskCacheFactory;
import com.bumptech.glide.load.engine.cache.LruResourceCache;
import com.bumptech.glide.load.engine.cache.MemorySizeCalculator;
import com.bumptech.glide.module.GlideModule;

/**
 * Created by ran on 2016/8/29.
 */
public class MyGlideModule implements GlideModule {
    @Override
    public void applyOptions(Context context, GlideBuilder builder) {
        //如果我们想要用默认值作为基准，然后调整它。比如，如果你认为你的 app 需要 20% 大的缓存作为 Glide 的默认值
        MemorySizeCalculator calculator = new MemorySizeCalculator(context);
        int defaultMemoryCacheSize = calculator.getMemoryCacheSize();
        int defaultBitmapPoolSize = calculator.getBitmapPoolSize();

        int customMemoryCacheSize = (int) (1.2 * defaultMemoryCacheSize);
        int customBitmapPoolSize = (int) (1.2 * defaultBitmapPoolSize);

        builder.setMemoryCache(new LruResourceCache(customMemoryCacheSize));
        builder.setBitmapPool(new LruBitmapPool(customBitmapPoolSize));

        // 设置了最大的大小为 100M
        int cacheSize100MegaBytes = 104857600;
        //2、磁盘缓存相关
        builder.setDiskCache(
//                new InternalCacheDiskCacheFactory(context, cacheSize100MegaBytes)//内部使用的磁盘缓存区
                new ExternalCacheDiskCacheFactory(context, cacheSize100MegaBytes)//外部可以访问的磁盘缓存区

        );
        //使用自定义的缓存路径
       // builder.setDiskCache(new DiskLruCacheFactory(downloadDirectoryPath, cacheSize100MegaBytes))

        ActivityManager activityManager =
                (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        //3、根据运行内存情况，自定义对图像的编码格式
        if(Build.VERSION.SDK_INT>=19){
            builder.setDecodeFormat(activityManager.isLowRamDevice() ?
                    DecodeFormat.PREFER_RGB_565 : DecodeFormat.PREFER_ARGB_8888);
        }
        else{
            builder.setDecodeFormat(DecodeFormat.PREFER_RGB_565);
        }
    }

    @Override
    public void registerComponents(Context context, Glide glide) {

    }
}
